package com.itheima.tliasmanagement.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tliasmanagement.dto.AddStudentDto;
import com.itheima.tliasmanagement.dto.StudentListDto;
import com.itheima.tliasmanagement.dto.UpdateStudentDto;
import com.itheima.tliasmanagement.entity.Student;
import com.itheima.tliasmanagement.exception.BizException;
import com.itheima.tliasmanagement.mapper.StudentMapper;
import com.itheima.tliasmanagement.service.StudentService;
import com.itheima.tliasmanagement.vo.PageBean;
import com.itheima.tliasmanagement.vo.StudentListVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageBean<StudentListVo> pageQuery(StudentListDto dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<StudentListVo> page = studentMapper.pageQuery(dto);
        return new PageBean(page.getTotal(), page.getResult());
    }

    @Override
    public void addStudent(AddStudentDto dto) {
        //判断重复，no phone idcard
        Student studentDB = studentMapper.selectByNoOrPhoneOrIdCard(dto.getNo(), dto.getPhone(), dto.getIdCard());
        if(studentDB != null){
            throw new BizException("学号、手机号、身份证号不能重复");
        }
        // 保存
        Student student = new Student();
        BeanUtils.copyProperties(dto, student);
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        student.setViolationCount((short)0);
        student.setViolationScore((short)0);
        studentMapper.insert(student);
    }

    @Override
    public StudentListVo getById(Integer id) {
        return studentMapper.selectById(id);
    }

    @Override
    public void updateStudent(UpdateStudentDto dto) {
        //判断重复，no phone idcard
        Student studentDB = studentMapper.selectByNoOrPhoneOrIdCard(dto.getNo(), dto.getPhone(), dto.getIdCard());
        if(studentDB == null){
           // 🆗、
        }else if(Objects.equals(studentDB.getId(), dto.getId())){
            //ok
        }else {
            throw new BizException("学号、手机号、身份证号不能重复");
        }
        Student student = new Student();
        BeanUtils.copyProperties(dto, student);
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);

    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        studentMapper.deleteByIds(ids);
    }

    @Override
    public void violation(Integer id, Integer score) {
        studentMapper.updateViolation(id, score);
    }
}
